<template>
  <div class="drawerContainer">
    <div class="chartRoom" ref="scrollContainer">
      <div class="messageInfo" v-if="messageList.length > 0">
        <div v-for="item in messageList">
          <div style="display: flex; justify-content: flex-start" v-if="item.name == 'report'">
            <img src="../assets/svg/report.svg" class="reportSvgIcon" alt="" />
            <div class="msgItem">
              <!-- <StreamMarkdown :content="reportMsgContent" :speed="200" /> -->
              <!-- {{ item.msg }} -->
              <div class="content" v-html="marked.parse(item.msg)"></div>
              <!-- <div class="content" v-html="marked.parse(reportMsgContent)"></div> -->
            </div>
          </div>
          <div style="display: flex; justify-content: flex-end" v-else>
            <div class="msgItem">
              <p>{{ item.msg }}</p>
            </div>
          </div>
        </div>
      </div>
      <div class="zhilutong" v-else>
        <div style="display: flex; align-items: center">
          <img src="../assets/svg/report.svg" class="reportSvg" alt="" />
          <div class="zltTitle">智路通</div>
        </div>
        <h2>嗨！我是智路通小助手</h2>
        <div class="text1">
          依托于deepseek智能引擎，结合深厚的公路基础知识库，为公路数字化提供智能检索决策支持
        </div>
      </div>
    </div>
    <div class="textarea" v-loading="loading">
      <el-input
        v-model="textarea"
        style="width: 100%"
        :autosize="{ minRows: 4, maxRows: 4 }"
        type="textarea"
        placeholder="给智路通发送消息"
        @keydown.enter.prevent="sendMsg"
      />
      <div class="btnclass">
        <el-button size="small" plain type="info" @click="clear">清空</el-button>
        <el-button size="small" plain type="primary" @click="sendMsg">发送</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { onMounted, ref, watch, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAvailableUnits } from "@/utils/pub.js";
import JSONBIG from "json-bigint";
import { marked } from "marked";
import StreamMarkdown from "@/components/StreamMarkdown.vue";
let messageList = ref([
  { name: "user", msg: "你好", thinkMsg: "" },
  {
    name: "report",
    msg: `一天内游玩杭州多个景点，可以按照以下有条理的计划进行：###1.**上午：西湖游览**-**景点推荐**：西湖、苏堤、白堤、断桥、雷峰塔、三潭印月。-**交通方式**：步行、租自行车或打车。-**时间安排**：上午8:00-12:00。-**建议**：西湖是杭州的标志性景点，可以步行或骑行环湖，欣赏湖光山色。建议提前购买西湖文化景观的联票，方便游览多个景点。###2.**中午：午餐**-**地点推荐**：西湖边的餐厅或湖畔居（推荐品尝杭州特色菜，如西湖醋鱼、龙井虾仁等）。-**时间安排**：中午12:00-13:00。###3.**下午：灵隐寺与飞来峰**-**景点推荐**：灵隐寺、飞来峰、永福寺。-**交通方式**：打车或公交（约30分钟）。-**时间安排**：下午13:30-17:00。-**建议**：灵隐寺是杭州著名的佛教寺庙，飞来峰是石刻艺术的宝库，建议预留足够时间游览。###4.**傍晚：河坊街与南宋御街**-**景点推荐**：河坊街、南宋御街、胡庆余堂。-**交通方式**：步行或打车。-**时间安排**：傍晚17:30-19:00。-**建议**：这两条街道是杭州的传统商业街区，可以品尝小吃、购买手工艺品，感受老杭州的风情。###5.**晚上：夜游钱塘江**-**景点推荐**：钱塘江夜景、杭州大剧院、杭州奥体中心。-**交通方式**：打车或公交。-**时间安排**：晚上19:30-21:00。-**建议**：夜晚的钱塘江灯光秀非常壮观，可以乘坐游船或步行沿江欣赏夜景。###6.**注意事项**-**提前规划**：建议提前查看景点开放时间和门票信息，避免高峰期拥堵。-**交通建议**：杭州市内交通便利，可以选择打车、公交或共享单车，节省时间。-**穿着建议**：杭州天气多变，建议携带适合的衣物，注意防晒和防雨。希望这个计划能帮助你轻松游玩杭州的多个景点，祝你旅途愉快！`,
    thinkMsg: ""
  },
  { name: "user", msg: "你好", thinkMsg: "" }
  //   {
  //     name: "report",
  //     msg: `
  // ### 把大象放进冰箱需要几步？
  // 这是一个幽默的比喻，用来说明看似复杂的事情其实可以简单处理。以下是步骤：
  // 1.打开冰箱门。
  // 2.把大象放进去。
  // 3.关上冰箱门。
  // 希望这个回答让您会心一笑！如果还有其他问题，欢迎随时提问！😄
  //     `,
  //     thinkMsg: ""
  //   }
]);
let textarea = ref("");
let loading = ref(false);
let scrollContainer = ref(null);
let baseUrl = ref(import.meta.env.VITE_BASE_URL);

onMounted(() => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
  }
});

const renderedHtml = (value) => {
  const fullContent = value.join("");
  return marked.parse(fullContent);
};
const splitIntoSegments = (md) => {
  // 正则：按空行（至少一个换行）拆分，保留分隔符（确保结构正确）
  return md.split(/(\n\s*\n)/).filter((segment) => segment.trim() !== "");
};

marked.setOptions({
  highlight: (code, lang) => {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value;
    }
    return hljs.highlightAuto(code).value;
  },
  gfm: true, // 支持GitHub风格Markdown
  breaks: true // 支持换行
});
const clear = () => {
  textarea.value = "";
};
const sendMsg = () => {
  if (textarea.value) {
    loading.value = true;
    messageList.value.push({ name: "user", msg: textarea.value, thinkMsg: "" });
    let params = { question: textarea.value };
    fetch(baseUrl.value + "ai/chat_in_stream?question=" + textarea.value, {
      method: "GET", // 或 POST、PUT 等
      headers: {
        // 在这里添加请求头键值对
        "Content-Type": "application/json",
        "X-TOKEN": sessionStorage.getItem("token")
      }
    }).then((response) => {
      textarea.value = "";
      messageList.value.push({ name: "report", msg: "", thinkMsg: "" });
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let allStr = "";
      let curIndex = 0;
      reader.read().then(function processText({ done, value }) {
        let curStr = decoder.decode(value);
        allStr += curStr;
        let { units, cursor } = getAvailableUnits(allStr, curIndex, done);
        if (units.length > 0) loading.value = false;
        curIndex = cursor;
        for (let unit of units) {
          let unitJs = JSONBIG({ storeAsString: true }).parse(unit);
          //// 业务-开始
          if (unitJs.code != 1000) {
            ElMessage(unitJs.msg);
          } else {
            let data = unitJs.data;
            console.log(data, "data");
            let msgType = data.msgType;
            let msgContent = data.msgContent;
            // if (msgType != "SESSION_COMPLETE") {
            //   messageList.value[messageList.value.length - 1].msg =
            //     messageList.value[messageList.value.length - 1].msg + msgContent;
            // }
            if (msgType == "AI_ANSWER") {
              // _this.summarizeFileData.content += msgContent;
              // let message = splitIntoSegments(msgContent);
              messageList.value[messageList.value.length - 1].msg += msgContent;
              console.log(
                messageList.value[messageList.value.length - 1].msg,
                "msgContentmsgContentmsgContentmsgContent"
              );
              // reportMsgContent.value = msgContent;
            } else if (msgType == "AI_THINK") {
              messageList.value[messageList.value.length - 1].thinkMsg +=
                "\n--深度思考内容----------------------\n";
              messageList.value[messageList.value.length - 1].thinkMsg += msgContent;
              messageList.value[messageList.value.length - 1].thinkMsg +=
                "\n--深度思考完成----------------------\n";
            }
          }
        }
        // if (done) _this.summarizeFileData.isIO = false;
        //// 业务-结束
        // if (!done) return reader.read().then(processText);
        if (done) return; //如果code ！= 1000，提前结束循环，不再解析
        nextTick(() => {
          if (scrollContainer.value) {
            scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
          }
        });
        return reader.read().then(processText);
      });
    });
  }
};
// const sendMsg = () => {
//   if (textarea.value) {
//     loading.value = true;
//     messageList.value.push({ name: "user", msg: textarea.value });
//     let params = { question: textarea.value };
//     fetch(baseUrl.value + "ai/chat_in_stream?question=" + textarea.value, {
//       method: "GET", // 或 POST、PUT 等
//       headers: {
//         // 在这里添加请求头键值对
//         "Content-Type": "application/json",
//         // Authorization: "Bearer your-token"
//         "X-TOKEN": sessionStorage.getItem("token")
//       }
//     }).then((response) => {
//       console.log(response, "response");
//       loading.value = false;
//       textarea.value = "";
//       messageList.value.push({ name: "report", msg: "" });
//       const reader = response.body.getReader();
//       reader.read().then(function processText({ done, value }) {
//         if (done) {
//           return;
//         }
//         // 将读取到的内容转换为字符串
//         let jsonString = new TextDecoder().decode(value);
//         let result = [];
//         try {
//           const singleObj = JSON.parse(jsonString);
//           result.push(singleObj);
//         } catch (error) {
//           const regex = /\{.*?\}/g;
//           const matches = jsonString.match(regex);
//           if (matches) {
//             matches.forEach((match) => {
//               try {
//                 const obj = JSON.parse(match);
//                 result.push(obj);
//               } catch (parseError) {
//                 console.error("解析 JSON 时出错:", parseError);
//               }
//             });
//           }
//         }
//         let raderDone = result.some((d) => {
//           console.log(d, "d");
//           if (d.code != 1000) {
//             ElMessage(d.msg);
//             return true;
//           }
//           // if (d.data.msgType != "SESSION_COMPLETE") {
//           if (d.data.msgType == "AI_ANSWER") {
//             messageList.value[messageList.value.length - 1].msg += d.data.msgContent;
//             console.log(
//               messageList.value[messageList.value.length - 1].msg,
//               "messageList.value[messageList.value.length - 1].msg"
//             );
//           }
//           return false;
//         });
//         if (raderDone) return; //如果code ！= 1000，提前结束循环，不再解析
//         nextTick(() => {
//           if (scrollContainer.value) {
//             scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight;
//           }
//         });
//         return reader.read().then(processText);
//       });
//     });
//   }
// };
</script>

<style lang="less" scoped>
.drawerContainer {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .chartRoom {
    flex: 1;
    border-radius: 8px;
    overflow-y: auto;

    .messageInfo {
      width: 100%;
      height: 100%;
      box-sizing: border-box;
      padding: 8px;
      font-size: 16px;

      .reportSvgIcon {
        width: 30px;
        height: 30px;
        margin-right: 10px;
      }

      .msgItem {
        margin-bottom: 20px;
        max-width: 80vw;
        background-color: rgb(239, 246, 255);
        padding: 5px 10px;
        box-sizing: border-box;
        border-radius: 10px;
      }
    }

    .zhilutong {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-top: 100px;
      .zltTitle {
        color: rgb(135, 178, 255);
        font-size: 46px;
        font-weight: 500;
      }

      .reportSvg {
        width: 60px;
        height: 60px;
        margin-right: 15px;
      }

      .text1 {
        font-size: 16px;
        color: rgb(55, 54, 54);
        padding: 0 30px;
        // text-align: center;
      }
    }
  }

  .textarea {
    height: 150px;
    box-sizing: border-box;
    border-radius: 5px;
    background-color: #f2f2f2;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 0 0 10px 0;
    margin: 0 1% 1% 1%;
  }

  :deep(.el-textarea__inner) {
    box-shadow: none;
    background-color: #f2f2f2;
    font-size: 16px;
  }

  .btnclass {
    box-sizing: border-box;
    padding: 0 10px;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
